<!--
 * @Author: HeAo
 * @Date: 2021-10-15 16:35:18
 * @LastEditTime: 2021-10-15 16:57:07
 * @LastEditors: HeAo
 * @Description: 
 * @FilePath: \web2103-2105\web2103code\3-2-Vue\day07\6-请求拦截.html
 * 别乱动！
-->
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="../js/axios.js"></script>
  <script>
    // 1.设置全局默认配置
    axios.defaults.baseURL = 'http://47.94.46.113:8888'

    // 2.设置请求拦截器
    axios.interceptors.request.use(config => {
      // Do something before request is sent
      // console.log(config);
      // 获取token
      const token = sessionStorage.getItem('token')
      // 判断请求目标路径只要不是登录接口，并且获取的token有值，把token设置到本次请求的请求头中
      if (config.url != '/user/login' && token) {
        config.headers['Authorization'] = token
      }
      return config;
    }, error => {
      // Do something with request error
      return Promise.reject(error);
    });

    // 3.设置响应拦截器
    axios.interceptors.response.use(response => {
      // Do something before response is sent
      // 将响应拦截下来，自定义内容后再返回
      console.log('重构之前', response);
      response = {
        ...response,
        data: response.data.data,
        statusText: response.data.message
      }
      return response;
    }, error => {
      // Do something with response error
      return Promise.reject(error);
    });

    // 4.发送请求
    axios.post('/user/login', {
      username: 'admin1',
      password: 123321
    }).then(res => {
      console.log('重构之后', res);
      sessionStorage.setItem('token', res.data.token)
    })

    // axios.post('/user/info', {
    //   username: 'admin1',
    //   password: 123321
    // }).then(res => {
    // })
  </script>
</head>

<body>

</body>

</html>